package test5.lupeng.jf.com.teamdemo.fragment;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.util.ArrayList;

import io.github.yavski.fabspeeddial.FabSpeedDial;
import io.github.yavski.fabspeeddial.FabSpeedDialBehaviour;
import io.github.yavski.fabspeeddial.SimpleMenuListenerAdapter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import test5.lupeng.jf.com.teamdemo.R;
import test5.lupeng.jf.com.teamdemo.activitys.BlogClassifyActivity;
import test5.lupeng.jf.com.teamdemo.activitys.WriteBlogActivity;
import test5.lupeng.jf.com.teamdemo.adapter.BlogAdapter;
import test5.lupeng.jf.com.teamdemo.bean.request.HotBlogBean;
import test5.lupeng.jf.com.teamdemo.bean.response.BlogResponse;
import test5.lupeng.jf.com.teamdemo.untils.HTTPUtils;
import test5.lupeng.jf.com.teamdemo.widget.TabBean;

/**
 * 学习
 * Created by C-yx on 2017/7/27.
 */

public class StudyFragment extends android.support.v4.app.Fragment {
    private static final String TAG = "StudyFragment";
    ArrayList<BlogResponse.ResultBean> mHotBlogResultBeen  =new ArrayList<>();
    private BlogAdapter mAdapter;
    String userId;
    private SmartRefreshLayout smartrefreshlayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View  view  = inflater.inflate(R.layout.fragment_study,container,false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        SharedPreferences sp = getContext().getSharedPreferences("config", Context.MODE_PRIVATE);
        userId = sp.getString("objectId", null);
        if(userId==null){
            userId="";
        }
        initView(view);
    }

    /**
     * 初始化视图
     * @param view
     */
    private  void initView(View view){
        RecyclerView rl_study= view.findViewById(R.id.rl_study);
        rl_study.setLayoutManager(new LinearLayoutManager(getContext()));

        //初始化头部视图
        ArrayList<TabBean> tabBeen =  new ArrayList<>();
        tabBeen.add(new TabBean("杂谈",R.drawable.ic_reader));
        tabBeen.add(new TabBean("提问",R.drawable.ic_help));
        tabBeen.add(new TabBean("分享",R.drawable.ic_movie));
        tabBeen.add(new TabBean("收藏夹",R.drawable.ic_assignment));

        View headView  = LayoutInflater.from(getContext()).inflate(R.layout.item_headview,null);
        headClick(headView);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        headView.setLayoutParams(params);

        mAdapter = new BlogAdapter(mHotBlogResultBeen);
        mAdapter.setHeadView(headView);
        rl_study.setAdapter(mAdapter);
        getData(userId,-1,10,0);

        FabSpeedDial fab_speed_dial=view.findViewById(R.id.fab_speed_dial);
        fab_speed_dial.setMenuListener(new SimpleMenuListenerAdapter(){
            @Override
            public boolean onMenuItemSelected(MenuItem menuItem) {
                String title = (String) menuItem.getTitle();
                int tag=0;
                switch (title){
                    case "杂谈":
                        tag=1;
                        break;
                    case "提问" :
                        tag=2;
                        break;
                    case "分享" :
                        tag=3;
                        break;
                }
                Intent intent = new Intent(getContext(), WriteBlogActivity.class);
                        intent.putExtra("tag",tag);
                getActivity().startActivity(intent);
                return false;
            }
        });

        smartrefreshlayout = view.findViewById(R.id.smartrefreshlayout);
        smartrefreshlayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getData(userId,-1,10,0);
                smartrefreshlayout.finishRefresh();
            }
        });
    }

    /**
     * 头布局的点击事件
     * @param headview
     */
    private  void headClick(View headview){
        headview.findViewById(R.id.ll_tt).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent  = new Intent(getContext(), BlogClassifyActivity.class);
                intent.putExtra("分类",1);
                getActivity().startActivity(intent);
            }
        });
        headview.findViewById(R.id.ll_helper).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent  = new Intent(getContext(), BlogClassifyActivity.class);
                intent.putExtra("分类",2);
                getActivity().startActivity(intent);
            }
        });
        headview.findViewById(R.id.ll_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent  = new Intent(getContext(), BlogClassifyActivity.class);
                intent.putExtra("分类",3);
                getActivity().startActivity(intent);
            }
        });
    }

    /**
     * 获取网络数据
     * @param userId   用户id
     * @param blogType 博客类型
     * @param limit     请求数量
     * @param timestamp 时间戳
     */
    private  void getData(String userId, int blogType,int limit , int timestamp ){
        HotBlogBean bean  = new HotBlogBean(userId,blogType,limit,timestamp);
        String url  = "https://leancloud.cn:443/1.1/functions/getBlogList";
        OkHttpClient client  = new OkHttpClient();
        Request request= HTTPUtils.requestPost(bean,url);
        client. newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
               if(response.code()==200){
                   String result = response.body().string();
                   //Log.e(TAG, "onResponse: "+result );
                   BlogResponse blogResponse = new Gson().fromJson(result,BlogResponse.class);
                   mHotBlogResultBeen.clear();
                   mHotBlogResultBeen.addAll(blogResponse.getResult());
                   getActivity().runOnUiThread(new Runnable() {
                       @Override
                       public void run() {
                           mAdapter.notifyDataSetChanged();
                       }
                   });
               }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getData(userId,-1,10,0);
    }
}
